package com.qu.waibao.home.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.google.gson.reflect.TypeToken;
import com.othershe.nicedialog.BaseNiceDialog;
import com.othershe.nicedialog.NiceDialog;
import com.othershe.nicedialog.ViewConvertListener;
import com.othershe.nicedialog.ViewHolder;
import com.qu.waibao.AppConfig;
import com.qu.waibao.R;
import com.qu.waibao.base.BaseActivity;
import com.qu.waibao.base.BaseRecyclerAdapter;
import com.qu.waibao.bean.PayResult;
import com.qu.waibao.bean.Shop;
import com.qu.waibao.home.adpater.ShopAdapter;
import com.qu.waibao.interf.XnetCallBack;
import com.qu.waibao.my.activity.CouponActivity;
import com.qu.waibao.network.ActionUtil;
import com.qu.waibao.network.NetManager;
import com.qu.waibao.search.ShopSearchActivity;
import com.qu.waibao.utils.GsonUtil;
import com.qu.waibao.utils.PayUitl;
import com.qu.waibao.utils.ToastUtil;
import com.qu.waibao.widget.RecyclerRefreshLayout;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import info.wangchen.simplehud.SimpleHUD;

public class ShopActivity extends BaseActivity implements View.OnClickListener,
        ShopAdapter.OnItemBuyClickListener,RecyclerRefreshLayout.SuperRefreshLayoutListener{
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.iv_publish)
    ImageView iv_publish;
    @BindView(R.id.mRecyclerRefreshLayout)
    RecyclerRefreshLayout mRecyclerRefreshLayout;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    private ShopAdapter adapter;
    private IWXAPI api;//微信支付参数
    private boolean isRefreshing = true;
    private int pageNum = 1;
    private String price = "";
    private String jifen = "";
    private String paytype = "";
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String ordercode = (String) msg.obj;
            int total = msg.arg1;
            dialogPayment(ordercode,total);
        }
    };
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.equals("com.qu.waibao.PAYMENTSUCCESS")){
                startActivity(new Intent(ShopActivity.this,CouponActivity.class));
                finish();
            }
        }
    };
    @Override
    protected int getContentView() {
        return R.layout.activity_shop;
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        tv_title.setText("商城");
        iv_publish.setImageResource(R.drawable.sy_top_fangdajing);
        mRecyclerRefreshLayout.setColorSchemeResources(R.color.colorPrimaryDark);
        mRecyclerRefreshLayout.setSuperRefreshLayoutListener(this);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.qu.waibao.PAYMENTSUCCESS");
        registerReceiver(receiver,intentFilter);
    }

    @Override
    protected void initData() {
        super.initData();
        adapter = new ShopAdapter(this, BaseRecyclerAdapter.ONLY_FOOTER);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setHasFixedSize(true);
        recyclerView.setNestedScrollingEnabled(false);
        recyclerView.setAdapter(adapter);
        if(adapter.getItems().size() == 0){
             mRecyclerRefreshLayout.setRefreshing(true);
             onRefreshing();
        }
        adapter.setOnItemBuyClickListener(this);
    }

    @OnClick({R.id.ll_back,R.id.iv_publish})
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ll_back:
                finish();
                break;
            case R.id.iv_publish:
                startActivity(new Intent(this, ShopSearchActivity.class));
                break;
        }
    }

    @Override
    public void onItemBuyClick(int position) {
        price = adapter.getItems().get(position).getPrice();
        jifen  = adapter.getItems().get(position).getJf();
        String quanid = adapter.getItems().get(position).getQuanid();
        goumai(quanid);
    }
    public void dialogPayment(final String ordercode, final int total){
        NiceDialog.init()
                .setLayoutId(R.layout.shop_dailog_layout)     //设置dialog布局文件
                .setConvertListener(new ViewConvertListener() {     //进行相关View操作的回调
                    @Override
                    public void convertView(final ViewHolder holder, final BaseNiceDialog dialog) {
                        TextView textView = holder.getView(R.id.tv_title);
                        textView.setText("支付"+jifen+"积分或"+price+"元");
                        holder.setText(R.id.tv_jifen,"积分抵扣(剩余积分"+total+")");
                        final TextView tv_weixin = holder.getView(R.id.tv_weixin);
                        final TextView tv_zhifubao = holder.getView(R.id.tv_zhifubao);
                        final TextView tv_jifen = holder.getView(R.id.tv_jifen);
                        holder.setOnClickListener(R.id.iv_close, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.dismiss();
                            }
                        });
                        holder.setOnClickListener(R.id.ll_weixin, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                tv_weixin.setTextColor(Color.parseColor("#67b8f2"));
                                tv_zhifubao.setTextColor(Color.parseColor("#333333"));
                                tv_jifen.setTextColor(Color.parseColor("#333333"));
                                paytype = "微信支付";
                            }
                        });

                        holder.setOnClickListener(R.id.ll_zhifubao, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                tv_weixin.setTextColor(Color.parseColor("#333333"));
                                tv_zhifubao.setTextColor(Color.parseColor("#67b8f2"));
                                tv_jifen.setTextColor(Color.parseColor("#333333"));
                                paytype = "支付宝支付";
                            }
                        });
                        holder.setOnClickListener(R.id.ll_jifen, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                tv_weixin.setTextColor(Color.parseColor("#333333"));
                                tv_zhifubao.setTextColor(Color.parseColor("#333333"));
                                tv_jifen.setTextColor(Color.parseColor("#67b8f2"));
                                paytype = "积分抵扣";
                            }
                        });
                        holder.setOnClickListener(R.id.tv_sure, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.dismiss();
                                if(paytype.equals("积分抵扣")){
                                    int jifens = Integer.valueOf(jifen);
                                    if(total >= jifens) {
                                        getOrderCode(ordercode, "积分抵扣");
                                    }else {
                                        ToastUtil.show(ShopActivity.this,"积分不足");
                                    }
                                }else {
                                    getOrderCode(ordercode,paytype);
                                }
                            }
                        });
                    }
                })
                .setDimAmount(0.3f)     //调节灰色背景透明度[0-1]，默认0.5f
                .setShowBottom(true)     //是否在底部显示dialog，默认flase
                .setOutCancel(true)     //点击dialog外是否可取消，默认true
                .show(getSupportFragmentManager());     //显示dialog
    }
    public void requestData(){
        Map<String,String> map = new HashMap<>();
        map.put("action", ActionUtil.quanshop_list_get);
        map.put("userid", AppConfig.getString("userid"));
        map.put("keyword","");
        map.put("pagenum",pageNum+"");
        NetManager.getInstance().request(this, map, false, new XnetCallBack() {
            @Override
            public void onSuccess(String result, String msg) {
               List<Shop> list = GsonUtil.createGson().fromJson(result,
                       new TypeToken<List<Shop>>(){}.getType());
               if(isRefreshing){
                   adapter.clear();
                   adapter.addAll(list);
                   if(list.size() < 12){
                       adapter.setState(BaseRecyclerAdapter.STATE_NO_MORE,true);
                   }
               }else {
                   adapter.addAll(list);
                   if(list.size() < 12){
                       adapter.setState(BaseRecyclerAdapter.STATE_NO_MORE,true);
                   }
                   if(list.size() == 0){
                       pageNum--;
                   }
               }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
               if(pageNum > 1){
                   pageNum--;
                   onCompalte();
               }
            }

            @Override
            public void onFinished() {
                onCompalte();
            }
        });
    }
    public void onCompalte(){
        mRecyclerRefreshLayout.onComplete();
        isRefreshing = false;
    }

    @Override
    public void onRefreshing() {
        isRefreshing = true;
        pageNum = 1;
        requestData();
    }

    @Override
    public void onLoadMore() {
        isRefreshing = false;
        pageNum++;
        adapter.setState(BaseRecyclerAdapter.STATE_LOAD_MORE,true);
        requestData();
    }

    public void goumai(String quanid){
        Map<String,String> map = new HashMap<>();
        map.put("action",ActionUtil.quan_bug_set);
        map.put("userid",AppConfig.getString("userid"));
        map.put("quanid",quanid);
        RequestParams params = NetManager.getUrl(map);
        x.http().post(params, new Callback.CommonCallback<String>() {

            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String ordercode = jsonObject.optString("ordercode");
                    String jf_total = jsonObject.optJSONObject("result").optString("jf_total");
                    Message message = mHandler.obtainMessage();
                    message.obj = ordercode;
                    message.arg1 = Integer.valueOf(jf_total);
                    mHandler.sendMessage(message);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    public void getOrderCode(String ordercode, final String paytype){
        SimpleHUD.showLoadingMessage(this,"",AppConfig.isCanCancel);
        Map<String,String> map = new HashMap<>();
        map.put("action",ActionUtil.order_pay_set);
        map.put("ordercode",ordercode);
        map.put("paytype",paytype);
        RequestParams params = NetManager.getUrl(map);
        x.http().post(params, new Callback.CommonCallback<String>() {

            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if(jsonObject.optInt("status") == 1) {
                        if (paytype.equals("微信支付")) {
                            String optString = jsonObject.optString("prepayinfo");
                            JSONObject payObj = new JSONObject(optString);
                            doWeiXinPay(payObj.optString("appid"), payObj.optString("partnerid"), payObj.optString("prepayid"), payObj.optString("noncestr"),
                                    payObj.optString("timestamp"), payObj.optString("package"), payObj.optString("sign"));

                        } else if(paytype.equals("支付宝支付")){
                            JSONObject payObj = jsonObject.optJSONObject("prepayinfo");
                            doAlipay("购买优惠卷", "购买优惠卷", payObj.optString("OrderCode"),
                                    payObj.optString("url_notify"), payObj.optString("partner"),
                                    payObj.optString("seller"), payObj.optString("private_key"));
                        }else if(paytype.equals("积分抵扣")) {
                            ToastUtil.show(ShopActivity.this,jsonObject.optString("message"));
                        }
                    }else {
                        ToastUtil.show(ShopActivity.this,jsonObject.optString("message"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                SimpleHUD.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                SimpleHUD.dismiss();
            }

            @Override
            public void onFinished() {
                SimpleHUD.dismiss();
            }
        });
    }

    public void doWeiXinPay(String appId, String partnerId, String prepayId, String nonceStr,
                            String timeStamp,String packageValue, String sign) {
        api = WXAPIFactory.createWXAPI(this,appId);
        api.registerApp(appId);
        PayReq req = new PayReq();
        req.appId= appId;
        req.partnerId= partnerId;
        req.prepayId= prepayId;
        req.nonceStr= nonceStr;
        req.timeStamp= timeStamp;
        req.packageValue= packageValue;
        req.sign= sign;
        api.sendReq(req);
    }
    public void doAlipay(String subject,String body,String out_trade_no,String notify_url,String partner
            ,String seller,String private_key) {
        // 订单
        String orderInfo = PayUitl.getOrderInfo(subject,body,out_trade_no, notify_url, "0.01",partner,seller);
        // 对订单做RSA 签名
        String sign = PayUitl.sign(orderInfo,private_key);
        try {
            // 仅需对sign 做URL编码
            sign = URLEncoder.encode(sign, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        // 完整的符合支付宝参数规范的订单信息
        final String payInfo = orderInfo + "&sign=\"" + sign + "\"&" + PayUitl.getSignType();

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造PayTask 对象
                SimpleHUD.dismiss();
                PayTask alipay = new PayTask(ShopActivity.this);
                // 调用支付接口，获取支付结果
                String result = alipay.pay(payInfo,true);
                PayResult payResult = new PayResult(result);
                final String resultStatus = payResult.getResultStatus();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                        if (TextUtils.equals(resultStatus, "9000")) {
                            ToastUtil.show(ShopActivity.this, "支付成功");
                            startActivity(new Intent(ShopActivity.this, CouponActivity.class));
                            finish();
                        }else if (TextUtils.equals(resultStatus, "8000")) {
                            // 判断resultStatus 为非“9000”则代表可能支付失败
                            // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                            ToastUtil.show(ShopActivity.this, "支付结果确认中");
                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            ToastUtil.show(ShopActivity.this, "支付失败");
                        }
                    }
                });

            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mHandler != null){
            mHandler = null;
        }
        if(receiver != null){
            unregisterReceiver(receiver);
            receiver = null;
        }
    }
}
